package  
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	import flash.utils.getTimer;
	
	import loader.ILoader;
	import loader.ILoaderBuilder;
	import loader.builders.SimpleLoaderBuilder;
	
	import pong.builders.PongLoaderBuilder;

	/**
	 * ...
	 * @author Luke Van In
	 */
	public class PongFuLoader extends MovieClip 
	{
		
		[Embed(source="../assets/pongfu-assets.swf", symbol="assets.Preloader")]
		private const SKIN_CLASS:Class;
		
		
		private const MIN_DISPLAY_TIME:Number = 1500;
		
		
		
		private var _loader:ILoader;
		
		private var _startTime:Number;
		
		
		public function PongFuLoader() 
		{
			if (stage) 
			{
				stage.scaleMode = StageScaleMode.NO_SCALE;
				stage.align = StageAlign.TOP_LEFT;
				this.opaqueBackground = 0;
			}
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			
			// start timing
			this._startTime = getTimer();
			
			
			// TODO show loader
			var skin:DisplayObjectContainer = new SKIN_CLASS() as DisplayObjectContainer;
			
			var builder:ILoaderBuilder = new PongLoaderBuilder(skin, this);
			
			this._loader = builder.buildLoader();
			
			this._loader.show();

		}
		
		private function ioError(e:IOErrorEvent):void 
		{
			trace(e.text);
		}
		
		private function progress(e:ProgressEvent):void 
		{
			this._loader.setProgress(e.bytesLoaded / e.bytesTotal);
		}
		
		private function checkFrame(e:Event):void 
		{
			var elapsedTime:Number = getTimer() - this._startTime;
			
			if ((currentFrame == totalFrames) && (elapsedTime >= this.MIN_DISPLAY_TIME))
			{
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void 
		{
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			this._loader.hide();
			
			this._loader.dispose();
			
			this._loader = null;
			
			startup();
		}
		
		private function startup():void 
		{
			var mainClass:Class = getDefinitionByName("PongFuMain") as Class;
			addChild(new mainClass() as DisplayObject);
		}
		
	}

}